﻿using System;
using System.Net;
using System.Text;
using Vidyano.Services;

namespace RapidDownloader.Model.Services.RapidShare
{
    partial class RapidShareDownloadProvider
    {
        private sealed class RapidShareFile : DownloadFile
        {
            #region Private Fields

            private string downloadLink, shortHost, serverId;
            private int status;

            #endregion

            #region Constructor

            internal RapidShareFile(string id, string fileName)
            {
                Id = id;
                FileName = fileName;

                Link = string.Format("http://rapidshare.com/files/{0}/{1}", Id, FileName);

                status = -1;
            }

            #endregion

            #region Properties

            public string Id { get; private set; }

            public override string Key
            {
                get { return "RS:" + Id + FileName; }
            }

            public override string ProviderIcon
            {
                get { return "/RapidDownloader.Modules.Views;component/DownloadModule/Resources/RapidShare.ico"; }
            }

            #endregion

            #region Commands

            protected override HttpWebRequest GetRequest()
            {
                var auth = ServiceLocator.GetService<IAuthenticatorService>();
                var req = (HttpWebRequest)WebRequest.Create(downloadLink);
                req.Timeout = 10 * 1000;
                req.ReadWriteTimeout = 10 * 1000;
                req.AllowAutoRedirect = true;
                req.Headers.Add("Authorization: Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(auth["UserName"].Value + ":" + auth["Password"].Value)));

                return req;
            }

            #endregion

            #region Private/Internal methods

            internal void UpdateServerStatus(string[] responseParts)
            {
                FileName = responseParts[0];
                Size = Convert.ToInt64(responseParts[1]);
                serverId = responseParts[2];
                status = Convert.ToInt32(responseParts[3]);
                CanDownload = status == 1 || status >= 50;
                shortHost = responseParts[4];
                Md5 = responseParts[5];

                downloadLink = string.Format("http://rs{0}{1}.rapidshare.com/files/{2}/{3}&directstart=1", serverId, shortHost, Id, FileName);
                Link = string.Format("http://rapidshare.com/files/{0}/{1}", Id, FileName);

                SendPropertyChanged(string.Empty);
            }

            #endregion
        }
    }
}